import APISER from '@/api'

let isUserInfoHasData = false
export default {
  state: {
    userInfo: {},
    cartList: [],
    infoNavs: [],
    siteConfig: {},
    siteMenu: [],
  },
  getters: {
    siteConfig: state => state.siteConfig,
    siteMenu: state => state.siteMenu,
    userInfo: state => state.userInfo,
    cartList: state => state.cartList,
    infoNavs: state => state.infoNavs,
  },
  actions: {
    // 获取网站配置信息
    getSiteconfigsInfo({ commit, state }) {
      APISER.getSiteconfigs().then(res => {
        if (res && res.code == 100) {
          // console.log(res)
          if (res && res.data && res.data.nav_list) {
            if (res.data.nav_list.menu_configs && res.data.nav_list.menu_configs.length > 0) {
              let temparr = res.data.nav_list.menu_configs
              temparr = temparr.filter(item => item.is_show)
              temparr.map(item => {
                if (item && item.functions && item.functions.length > 0) {
                  item.functions = item.functions.filter(item1 => item1.is_show)
                }
              })
              commit('SAVE_SITE_MENU', temparr)

            }
          }
          commit('SAVE_SITE_CONFIG', res.data)
        }
      })
    },
    // 获取用户数据
    getUserInfo ({ commit, state }) {
      if (isUserInfoHasData) {
        return state.userInfo
      }
      isUserInfoHasData = true
      APISER.getUserInfo().then(({ data }) => {
        commit('SAVE_USER_INFO', data)
      })
    },
    // 清除用户信息
    clearUserInfo({commit}) {
      commit('SAVE_USER_INFO', {})
    },
    // 获取购物车列表
    getCartList ({ commit, state }, opts) {
      APISER.getCartList().then(res => {
        console.log(res)
        if (res.code == 100) {
          // 默认选中
          res.data.map(item => {
            item.isSelect = true
          })
          commit('SAVE_CART_LIST', res.data)
        }
      })
    },
    // 获取新闻资讯的分类类型
    getInfoType({ commit, state }) {
      if (state.infoNavs && state.infoNavs.length === 0) {
        APISER.getInfoTags().then(res => {
          if (res.code == 100) {
            commit('SAVE_INFO_TAGS', res.data)
          }
        })
      }
    },

  },
  mutations: {
    SAVE_SITE_CONFIG (state, data) {
      state.siteConfig = data
    },
    SAVE_SITE_MENU (state, data) {
      state.siteMenu = data
    },
    SAVE_USER_INFO (state, data) {
      state.userInfo = data
    },
    SAVE_CART_LIST (state, data) {
      state.cartList = data
    },
    SAVE_INFO_TAGS (state, data) {
      state.infoNavs = data
    },
  }
}
